// Fill out your copyright notice in the Description page of Project Settings.


#include "MySword.h"
#include "PlayerCharacter.h"
#include "Weapon.h"
#include "Components\SphereComponent.h"

AMySword::AMySword() 
{
	MySword = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MySword"));
	MySword->SetupAttachment(RootComponent);
}

void AMySword::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp,
	int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) 
{
	Super::OnOverlapBegin(OverlappedComponent, OtherActor, OtherComp, OtherBodyIndex, bFromSweep, SweepResult);
	if (OtherActor)
	{
		APlayerCharacter* Player = Cast<APlayerCharacter>(OtherActor);
		if (Player)
		{
			if (Player->OverlapWeapon == nullptr)
			{
				Player->OverlapWeapon = this;
			}
			TArray<FStringFormatArg> FormatArray;
			FormatArray.Add(GetName());
			GEngine->AddOnScreenDebugMessage(-1, 100, FColor::Blue, FString::Format(TEXT("Press F Equip {0}"), FormatArray),
				true, FVector2D(4, 4));
		}
	}
}

void AMySword::OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp,
	int32 OtherBodyIndex) 
{
	Super::OnOverlapEnd(OverlappedComponent, OtherActor, OtherComp, OtherBodyIndex);
	if (OtherActor)
	{
		APlayerCharacter* Player = Cast<APlayerCharacter>(OtherActor);
		if (Player)
		{
			if (Player->OverlapWeapon == this)
			{
				Player->OverlapWeapon = nullptr;
			}
			GEngine->ClearOnScreenDebugMessages();
		}
	}
}

void AMySword::EquipWeapon(class APlayerCharacter* Player)
{
	if (Player)
	{
		MySword->SetCollisionResponseToChannels(ECR_Ignore);
		MySword->SetSimulatePhysics(false);
		AttachToComponent(Player->GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale, "weapon");
		SphereComp->OnComponentBeginOverlap.RemoveDynamic(this, &AWeapon::OnOverlapBegin);
		SphereComp->OnComponentEndOverlap.RemoveDynamic(this, &AWeapon::OnOverlapEnd);
		GEngine->ClearOnScreenDebugMessages();
		Player->SetSweapWeapon(this);
	}
}
